package com.lovezy.platform.message.push.instance;

import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.IQueryResult;
import com.gexin.rp.sdk.base.ITemplate;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.LinkTemplate;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.style.Style0;
import com.lovezy.platform.core.utils.JsonUtil;
import com.lovezy.platform.message.push.PushEntity;
import com.lovezy.platform.message.push.PushMessage;
import com.lovezy.platform.message.push.PushResponse;
import com.lovezy.platform.message.push.Pusher;
import com.lovezy.platform.message.push.SinglePushMessage;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by jin on 2017/12/7.
 */
@ConfigurationProperties(prefix = "app.push.igetui")
@Getter
@Setter
@ToString
public class IgetuiPush implements Pusher {

    private final Log log = LogFactory.getLog(IgetuiPush.class);

    private String appId;
    private String appKey;
    private String masterSecret;
    private String api;


    @Override
    public PushResponse push(PushMessage message) {

        IGtPush push = new IGtPush(api, appKey, masterSecret);


        IPushResult ret;
        if (message instanceof SinglePushMessage) {
            SinglePushMessage singlePushMessage = (SinglePushMessage) message;
            ret = pushToSingle(push, singlePushMessage);
            IQueryResult badgeResult = push.setBadgeForCID("+1", appId, Collections.singletonList(singlePushMessage.getId()));
            if (log.isDebugEnabled()) {
                log.debug("个推 badge 设置 -> " + badgeResult.getResponse());
            }
        }else{
            ret = pushToApp(push, message);
        }

        String result = ret.getResponse().toString();
        return new PushResponse(true, result);
    }

    private IPushResult pushToApp(IGtPush push, PushMessage message) {
        List<String> appIds = new ArrayList<>();
        appIds.add(appId);

        // 定义"AppMessage"类型消息对象，设置消息内容模板、发送的目标App列表、是否支持离线发送、以及离线消息有效期(单位毫秒)
        AppMessage appMessage = new AppMessage();
        appMessage.setData(buildAppTemplate(message));
        appMessage.setAppIdList(appIds);
        appMessage.setOffline(true);
        appMessage.setOfflineExpireTime(1000 * 600);
        try {
            return push.pushMessageToApp(appMessage);
        } catch (RequestException e) {
            log.error("个推推送APP消息失败", e);
            return push.pushMessageToApp(appMessage, e.getRequestId());
        }
    }

    private IPushResult pushToSingle(IGtPush push, SinglePushMessage message) {

        SingleMessage singleMessage = new SingleMessage();
        singleMessage.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        singleMessage.setOfflineExpireTime(24 * 3600 * 1000);
        singleMessage.setData(buildTemplate(message));

        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        singleMessage.setPushNetWorkType(0);
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(message.getId());
        try {
            return push.pushMessageToSingle(singleMessage, target);
        } catch (RequestException e) {
            log.error("个推推送单条消息失败", e);
            return push.pushMessageToSingle(singleMessage, target, e.getRequestId());
        }
    }

    private ITemplate buildAppTemplate(PushMessage message) {
        LinkTemplate template = new LinkTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setUrl("");

        Style0 style = new Style0();
        // 设置通知栏标题与内容
        style.setTitle(message.getTitle());
        style.setText(message.getContent());

        // 配置通知栏图标
//        style.setLogo("icon.png");
        // 设置通知是否响铃，震动，或者可清除
        style.setRing(true);
        style.setVibrate(true);
        style.setClearable(true);
        template.setStyle(style);

        return template;

    }

    private ITemplate buildTemplate(PushMessage message) {
        NotificationTemplate template = new NotificationTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(1);
        PushEntity entity = message.getEntity();
        template.setTransmissionContent(JsonUtil.toJson(entity));


        Style0 style = new Style0();
        style.setTitle(message.getTitle());
        style.setText(message.getContent());
        style.setClearable(true);
        style.setRing(true);
        style.setVibrate(true);

        template.setStyle(style);

        return template;
    }


}
